
/*
 * @Author: hanxin 
 * @Date: 2021-08-28 23:07:02 
 * @Last Modified by: hanxin
 * @Last Modified time: 2021-08-28 23:24:59
 * 使用德鲁伊连接池的一个jdbc工具类
 */

package mhl.util;

import java.io.FileInputStream;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

public class jdbcutilsBydruid {

    private static DataSource dataSource;

    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            //将编译异常转换为 运行异常抛出,程序员可以选择不处理该异常
            throw new RuntimeException(e);
        }
    }

    public static java.sql.Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 若形参不为空就关闭连接 不同于jdbc直接连接,用连接池缓存的连接关闭只是将连接交还给连接池
     * 
     * @param resultset
     * @param statement
     * @param connection
     */
    public static void close(java.sql.ResultSet resultset, java.sql.Statement statement,
            java.sql.Connection connection) {

        try {
            if (resultset != null) {
                connection.close();
            }
            if (statement != null) {
                connection.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
